const OSS = require('ali-oss')
const moment = require('moment')
import Cookies from 'js-cookie'
import Config from '@/settings'

let expirationTime = null // STS token 过期时间
let client = null // OSS Client 实例

const OSSConfigKey = Config.OSSConfigKey

// 保存config
export function setOssConfig(config) {
  return Cookies.set(OSSConfigKey, JSON.stringify(config))
}

// 获取config
export function getConfig() {
  return JSON.parse(Cookies.get(OSSConfigKey))
}

// 获取前缀
export function getPrefix() {
  return getConfig().prefix
}

// 初始化 oss client
export function initOssClient(accessKeyId, accessKeySecret, stsToken, expiration) {
  const config = getConfig()

  console.info('当前oss的配置信息为(如下):')
  console.info(config)

  client = new OSS({ accessKeyId, accessKeySecret, stsToken, region: config.region, bucket: config.bucket })
  expirationTime = expiration
  return client
}

// 检查 oss 实例以及过期时间
export function checkOssClient() {
  const current = moment()
  return moment(expirationTime).diff(current) < 0 ? null : client
}

// 用于 sts token 失效、用户登出时注销 oss client
export function destroyOssClient() {
  client = null
}
